<template>
  <div class="post-container">
    <!-- 返回按钮 -->
    <div class="back-button">
      <el-button type="text" @click="goBack" icon="el-icon-arrow-left">
        返回帖子列表
      </el-button>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-icon class="is-loading">
        <i class="el-icon-loading"></i>
      </el-icon>
      <span style="margin-left: 10px;">正在加载帖子详情...</span>
    </div>

    <!-- 用户信息区域 -->
    <div class="user-info" v-if="!loading">
      <el-avatar :src="postDetail.userInfo.avatar"></el-avatar>
      <div class="user-info-right">
        <div class="user-name">{{ postDetail.userInfo.username }}</div>
      </div>
      <div class="user-actions">
        <el-button v-if="!isAuthor && !isFollow" size="mini" @click="follow">关注</el-button>
        <el-button v-if="!isAuthor && isFollow" size="mini" @click="cancelFollow">取消关注</el-button>
        <el-button v-if="isAuthor" size="mini" type="danger" @click="deletePost">删除</el-button>
      </div>
    </div>

    <div class="post-time">{{ postDetail.createTime }}</div>

    <el-divider></el-divider>

    <!-- 帖子标题和内容 -->
    <div class="post-title">{{ postDetail.title }}</div>
    <div class="post-content" v-html="postDetail.content"></div>


    <!-- 交互按钮 -->
    <div class="post-actions">
      <el-button @click="toggleCollection">
        <i :class="{'el-icon-star-on': isCollected,
                    'el-icon-star-off': !isCollected}"></i>
        <span>{{ postDetail.collectionCount }}</span>
      </el-button>
      <el-button @click="copyShareLink">
        <i class="el-icon-share"></i>
        <span> 复制链接</span>
      </el-button>
    </div>

    <!-- 分割线 -->
    <el-divider></el-divider>

    <!-- 评论区 -->
    <div class="comment-list-container">
      <!-- 主评论列表 -->
      <ul class="comment-list">
        <!-- 遍历每一条根评论 -->
        <li  v-for="(comment, index) in commentList" :key="index" class="comment-item">
          <!-- 引入根评论组件 -->
          <CommentRoot
            :comment="comment"
            :blog="postDetail"
            :get-comment-list="getCommentList"
          />
        </li>
      </ul>
    </div>

    <!-- 评论输入框 -->
    <div class="comment-input-section">
      <div class="comment-input">
        <el-input
          type="input"
          placeholder="写下你的评论..."
          v-model="form.content"
          :rows="4"
          resize="none"
        ></el-input>
        <div class="comment-input-actions">
          <el-button size="small" @click="clearComment">清空</el-button>
          <el-button type="primary" size="small" @click="addComment" :disabled="!form.content.trim() || submitting">
            {{ submitting ? '发布中...' : '发布评论' }}
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import {delPosts, getPosts, updatePosts} from "@/api/forum/posts";
import {addComments, getTreeList} from "@/api/forum/comments";
import CommentRoot from "@/views/forum/CommentRoot.vue";
import "@/assets/styles/comment.css"
import {addFollowing, delFollowing, listFollowingByUserId} from "@/api/forum/following";
import {getInfo} from "@/api/login";
import {addLikePosts, delLikePosts, listLikePosts} from "@/api/forum/likePosts";

export default {
  name:"detail",
  created() {
    this.getPostDetail();
    this.getCommentList()
    this.isFollowing()
    this.toggleCollection()
    this.checkCollectionStatus()
  },
  components: {
    CommentRoot
  },
  data() {
    return {
      // 查询帖子详情
      postDetail: {
        userInfo: {},
        title: null,
        userId: null,
        name: null,
        content: null,
        likes: null,
        comments: null,
        imageUrl: null,
        viewCount: null,
        createdAt: null,
      },
      blog:{},
      isCollected: false, // 是否已收藏
      commentList: [],
      form: {
        content: ''
      },
      showShare: false,
      isFollow: false,
      isAuthor: false,
      loading: false, // 防止重复点击
      submitting: false, // 提交状态
        // 查询评论参数
      queryCommentParams: {
        postId: null,
        userId: null,
        content: null,
        createdAt: null,
        updatedAt: null,
        parentCommentId: null,
        status: null,
        userName: null,
      },
      //关注用户数据
      queryFollowingParams: {
        userId: null,
        followedUserId: null,
        createdAt: null,
        status: null,
      },
      followList:[],
      // 查询收藏帖子参数
      likeList: {
        userId: null,
        postId: null,
        createdAt: null,
      },
      collectionList:[]
    };
  },
  methods: {
    // 获取帖子详情
    getPostDetail() {
      const postId = this.$route.params.id;
      if (!postId) {
        this.$message.error('帖子ID不能为空');
        this.$router.push({name: 'first'}).catch(err => {
          if (err.name === 'NavigationDuplicated') {
            console.log('重复导航被忽略');
            return;
          }
          throw err;
        });
        return;
      }

      this.loading = true;
      getPosts(postId).then(response => {
        this.postDetail = response.data || {};
        // 设置用户信息
        this.postDetail.userInfo = {
          username: this.postDetail.name || '匿名用户',
          avatar: this.$store.getters.avatar
        };

        getInfo().then(response => {
          // 判断是否为作者
          const currentUserId = response.user.userId;
          if (this.postDetail.userId === currentUserId) {
            this.isAuthor = true;
          }
        })
        this.loading = false;
      }).catch(error => {
        console.error('获取帖子详情失败:', error);
        this.$message.error('获取帖子详情失败');
        this.loading = false;
        this.$router.push({name: 'first'}).catch(err => {
          if (err.name === 'NavigationDuplicated') {
            console.log('重复导航被忽略');
            return;
          }
          throw err;
        });
      });
    },
    // 获取评论列表
    getCommentList() {
      this.queryCommentParams.postId = this.$route.params.id;
      if (!this.queryCommentParams.postId) {
        this.$message.error('帖子ID不能为空');
        return;
      }
      getTreeList(this.queryCommentParams).then(response => {
        this.commentList = response.rows || [];

      }).catch(error => {
        console.error('获取评论列表失败:', error);
        this.$message.error('获取评论列表失败');
      });
    },
    // 是否已关注
    isFollowing() {
      // 获取当前用户id
      getInfo().then(response => {
        this.queryFollowingParams.userId = response.user.userId;
        // 获取关注的用户列表
        listFollowingByUserId(this.queryFollowingParams).then(response => {
          this.followList = response.rows.map(item => item.followedUserId);
          this.isFollow = this.followList.includes(this.queryFollowingParams.userId);
        }).catch(error => {
          console.error("查询用户失败:", error);
        });
      }).catch(error => {
        console.error("获取用户信息失败:", error);
      });

    },
    // 关注用户
    follow() {
      this.queryFollowingParams.followedUserId = this.postDetail.userId;
      console.log("id", this.queryFollowingParams);
      addFollowing(this.queryFollowingParams).then(response => {
      })
      this.isFollow = true;
      this.$message.success('关注成功');
    },
    // 取消关注
    cancelFollow() {
      this.queryFollowingParams.followedUserId = this.postDetail.userId;
      console.log("id", this.queryFollowingParams.followedUserId);
      delFollowing(this.queryFollowingParams.followedUserId).then(response => {
        console.log("deleteFollowing", response);
      })
      this.isFollow = false;
      this.$message.success('已取消关注');
    },
    // 删除帖子
    deletePost() {
      this.$confirm('确定要删除该帖子吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 用户点击了【确定】，调用删除 API
        delPosts(this.$route.params.id).then(response => {
          this.$message.success('删除成功');
          // 删除成功后跳转到首页或其他页面
          this.$router.push({name: 'first'}).catch(err => {
            if (err.name === 'NavigationDuplicated') {
              console.log('重复导航被忽略');
            } else {
              throw err;
            }
          });
        })
          .catch(error => {
            this.$message.error('删除失败，请重试');
            console.error("删除帖子失败：", error);
          });

      }).catch(() => {
        // 用户点击了【取消】或点击遮罩层等，不执行任何操作
        // 只需留空即可，对话框会自动关闭
      });
    },
    // 收藏列表
    checkCollectionStatus() {
      this.likeList.postId=this.$route.params.id;
      listLikePosts( this.likeList).then(response => {
        this.collectionList = response.rows || [];
        this.isCollected = this.collectionList.length > 0;
        console.log("res", this.collectionList)
      })
      },
    // 切换收藏状态
     toggleCollection() {
       this.likeList.postId=this.$route.params.id;
       if (this.loading) return;
       this.loading = true;

       if (this.isCollected) {
         // 取消收藏
         const favoriteId = this.collectionList[0].favoriteId;
         delLikePosts(favoriteId).then(() => {
           this.postDetail.likes--;
           updatePosts(this.postDetail).then(() => {
           })
           this.isCollected = false;
           this.$message.success('已取消收藏');
         }).finally(() => {
           this.loading = false;
         })

       } else {
         // 添加收藏
         addLikePosts(this.likeList).then(() => {
           this.postDetail.likes++;
           updatePosts(this.postDetail).then(() => {
           })
           this.isCollected = true;
           this.$message.success('已收藏');
         }).finally(() => {
           this.loading = false;
         })
       }
     },
    // 发布评论
    async addComment() {
      if (!this.form.content.trim()) {
        this.$message.warning('评论内容不能为空');
        return;
      }

      if (this.submitting) return;

      this.submitting = true;

      try {
        const commentData = {
          postId: this.$route.params.id,
          content: this.form.content.trim(),
          parentCommentId: null // 主评论
        };

        console.log('提交主评论:', commentData);

        const response = await addComments(commentData);

        if (response.code === 200) {
          this.$message.success('评论发布成功');
          // 重新获取评论列表
          this.getCommentList();
          this.form.content = '';
        } else {
          this.$message.error(response.msg || '评论发布失败');
        }
      } catch (error) {
        console.error('评论发布失败:', error);
        this.$message.error('评论发布失败，请稍后重试');
      } finally {
        this.submitting = false;
      }
    },
    // 清空评论
    clearComment() {
      this.form.content = '';
    },
    // 点赞评论
    toggleThumbs(commentId, index) {
      this.commentList[index].thumbs++;
      this.$message.success('点赞成功');
    },
    // 加载更多评论
    loadMoreComments() {
      this.hasMoreComments = false;
      this.$message.info('已加载全部评论');
    },
    // 复制分享链接
    copyShareLink() {
      const input = document.createElement('input');
      document.body.appendChild(input);
      input.value = window.location.href;
      input.select();
      document.execCommand('copy');
      document.body.removeChild(input);
      this.$message.success('链接已复制');
      this.showShare = false;
    },
    // 返回上一页
    goBack() {
      // 如果历史记录中有上一页，则返回，否则跳转到首页
      if (window.history.length > 1) {
        this.$router.go(-1);
      } else {
        this.$router.push({ name: 'first' }).catch(err => {
          if (err.name === 'NavigationDuplicated') {
            console.log('重复导航被忽略');
            return;
          }
          throw err;
        });
      }
    },
  }
};
</script>

<style scoped>
.post-container {
  max-width: 100%;
  margin: 0 auto;
  padding:0 20px;
}

.back-button {
  margin-bottom: 20px;
}

.back-button .el-button {
  color: #2e8b57;
  font-size: 14px;
}

.back-button .el-button:hover {
  color: #3cb371;
}

.loading-container {
  text-align: center;
  padding: 40px 0;
  color: #666;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.user-info-right {
  flex: 1;
  margin-left: 15px;
}

.user-name {
  font-size: 16px;
  font-weight: bold;
}

.user-intro {
  font-size: 12px;
  color: #999;
}

.user-actions {
  margin-left: 15px;
}

.post-time {
  font-size: 12px;
  color: #999;
  margin-bottom: 10px;
}

.post-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 15px;
}

.post-content {
  margin-bottom: 15px;
  line-height: 1.5;
}

.post-images {
  margin-bottom: 15px;
}

.post-actions {
  display: flex;
  margin-bottom: 15px;
}

.comments-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
}

.comment-item {
  display: flex;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.comment-user {
  font-weight: bold;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

.comment-actions {
  margin-top: 5px;
}

.comment-input {
  margin-top: 20px;
  display: flex;
}

.comment-input .el-textarea {
  flex: 1;
  margin-right: 10px;
}

.share-options {
  display: flex;
  justify-content: space-around;
}

</style>
